// 用户相关的状态管理

import { createSlice } from "@reduxjs/toolkit"
import { removeToken, request } from "@/utils"
import { setToken as _setToken, getToken } from "@/utils"
import { loginAPI, getProfileAPI } from "@/apis/user"

const userStore = createSlice({
  name: "user",
  // 数据状态
  initialState: {
    token: getToken() || '',
    userInfo: {}
  },
  // 同步修改方法
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      
      // 持久化存储
      _setToken(action.payload)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    // 退出登录
    clearUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  }
})

// 结构actionCreator
const { setToken,setUserInfo, clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步方法 完成登录获取token
const fetchLogin = (LoginForm) => {
  return async (dispatch) => {
    // 异步请求
    const res = await loginAPI(LoginForm)
    // 假设登录成功后返回token
    dispatch(setToken(res.data.token))
  }
}

// 获取个人用户信息异步方法
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}

export { setToken, fetchLogin,fetchUserInfo, clearUserInfo }
export default userReducer